package com.ncmmall.mall.controller.business.distribution;

import com.ncmmall.application.business.distribution.DistributionPosterApplication;
import com.feijin.commons.lang.Requires;
import com.ncmmall.domain.business.distribution.DistributionPoster;
import com.ncmmall.domain.business.distribution.QDistributionPoster;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 分销海报管理
 *
 * @author likaikai
 * @date 2020-08-24 07:13:06
 */
@Controller
@RequestMapping("/distribution/poster")
@Slf4j
public class DistributionPosterController {

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private DistributionPosterApplication distributionPosterApplication;

    @Value("${store.domain}")
    private String storeDomain;

    /**
     * 海报列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model, PageParams pageParams, DistributionPoster params) {

        WebUser user = Securitys.currentUser();

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo()).setPageSize(pageParams.getPageSize());
        String hql = "select g from DistributionPoster g where g.merchant.id = :mid";
        Map<String, Object> map = new HashMap<>();
        map.put("mid", user.getId());

        if (params.getStatus() != null) {
            hql += " and g.status = :status";
            map.put("status", params.getStatus());
        }

        if (params.getType() != null) {
            hql += " and g.type = :type";
            map.put("type", params.getType());
        }

        hql += " order by g.createTime desc";

        QueryPage<DistributionPoster> page = queryChannelService.findPage(hql, pageRequest.setParams(map), DistributionPoster.class);
        model.addAttribute("page", page);
        model.addAttribute("params", params);

        return "merchant/distribution/poster/list";
    }


    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String detail(Model model, long id) {
        DistributionPoster poster = queryChannelService.findOne(DistributionPoster.class, id);
        model.addAttribute("poster", poster);
        return "merchant/distribution/poster/detail";
    }

    /**
     * 删除海报
     *
     * @param id 海报id
     */
    @RequestMapping(value = "/remove", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> remove(long id) {
        try {
            DistributionPoster poster = queryChannelService.findOne(DistributionPoster.class, id);
            Requires.notNull(poster, "海报不存在");

            distributionPosterApplication.remove(poster);
            return ImmutableMap.of("status", true, "message", "删除成功");

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[删除海报异常]", e);
            return ImmutableMap.of("status", false, "message", "删除异常");
        }
    }


    /**
     * 上架海报
     *
     * @param id 海报id
     */
    @RequestMapping(value = "/enable", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> enable(long id) {
        try {
            DistributionPoster poster = queryChannelService.findOne(DistributionPoster.class, id);
            Requires.notNull(poster, "海报不存在");
            Requires.isTrue(poster.getStatus() == 2, "海报未审核通过");

            distributionPosterApplication.enable(poster);
            return ImmutableMap.of("status", true, "message", "上架成功");

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[上架海报异常]", e);
            return ImmutableMap.of("status", false, "message", "上架异常");
        }
    }


    /**
     * 下架海报
     *
     * @param id 海报id
     */
    @RequestMapping(value = "/disable", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> disable(long id) {
        try {
            DistributionPoster poster = queryChannelService.findOne(DistributionPoster.class, id);
            Requires.notNull(poster, "海报不存在");

            distributionPosterApplication.disable(poster);
            return ImmutableMap.of("status", true, "message", "下架成功");

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[下架海报异常]", e);
            return ImmutableMap.of("status", false, "message", "下架异常");
        }
    }

    /**
     * 提交审核海报
     *
     * @param id 海报id
     */
    @RequestMapping(value = "/applyCheck", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> applyCheck(long id) {
        try {
            DistributionPoster poster = queryChannelService.findOne(DistributionPoster.class, id);
            Requires.notNull(poster, "海报不存在");

            distributionPosterApplication.applyCheck(poster);
            return ImmutableMap.of("status", true, "message", "提交审核成功");

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[提交审核海报异常]", e);
            return ImmutableMap.of("status", false, "message", "提交审核异常");
        }
    }

    /**
     * 批量删除海报
     *
     * @param ids 海报id
     */
    @RequestMapping(value = "/removes", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> remove(String ids) {

        try {

            List<Long> longIds = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(ids).stream().map(Long::valueOf).collect(Collectors.toList());
            Requires.notEmpty(longIds, "请选择海报");

            List<DistributionPoster> distributionGoodsList = queryChannelService.findAll(QDistributionPoster.distributionPoster.id.in(longIds), DistributionPoster.class);
            distributionPosterApplication.removes(distributionGoodsList);

            return ImmutableMap.of("status", true, "message", "删除成功");

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[批量删除海报异常]", e);
            return ImmutableMap.of("status", false, "message", "删除异常");
        }
    }

    /**
     * 批量上架海报
     *
     * @param ids 海报id
     */
    @RequestMapping(value = "/enables", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> enables(String ids) {

        try {

            List<Long> longIds = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(ids).stream().map(Long::valueOf).collect(Collectors.toList());
            Requires.notEmpty(longIds, "请选择海报");

            List<DistributionPoster> distributionGoodsList = queryChannelService.findAll(QDistributionPoster.distributionPoster.id.in(longIds), DistributionPoster.class);
            distributionPosterApplication.enables(distributionGoodsList);

            return ImmutableMap.of("status", true, "message", "上架成功");

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[批量上架海报异常]", e);
            return ImmutableMap.of("status", false, "message", "上架异常");
        }
    }

    /**
     * 批量下架海报
     *
     * @param ids 海报id
     */
    @RequestMapping(value = "/disables", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> disables(String ids) {

        try {

            List<Long> longIds = Splitter.on(";").omitEmptyStrings().trimResults().splitToList(ids).stream().map(Long::valueOf).collect(Collectors.toList());
            Requires.notEmpty(longIds, "请选择海报");

            List<DistributionPoster> distributionGoodsList = queryChannelService.findAll(QDistributionPoster.distributionPoster.id.in(longIds), DistributionPoster.class);
            distributionPosterApplication.disables(distributionGoodsList);

            return ImmutableMap.of("status", true, "message", "下架成功");

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[批量下架海报异常]", e);
            return ImmutableMap.of("status", false, "message", "下架异常");
        }
    }


    /**
     * 添加海报
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model) {
        model.addAttribute("poster", new DistributionPoster())
                .addAttribute("_method", "POST");

        return "merchant/distribution/poster/form";
    }

    /**
     * 添加海报
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> create(DistributionPoster params) {
        try {
            Requires.hasLength(params.getBackground(), "请上传背景图片");
            params.setMerchant(Securitys.currentUser())
                    .setPlatform(2)
                    .setStatus(3);
            distributionPosterApplication.create(params);
            return ImmutableMap.of("status", true, "message", "添加成功");
        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[添加海报异常]", e);
            return ImmutableMap.of("status", false, "message", "添加异常");
        }
    }

    /**
     * 编辑海报
     */
    @RequestMapping(value = "/{id}/modify", method = RequestMethod.GET)
    public String create(Model model, @PathVariable("id") long id) {

        model.addAttribute("poster", queryChannelService.findOne(DistributionPoster.class, id))
                .addAttribute("_method", "PUT");
        return "merchant/distribution/poster/form";
    }

    /**
     * 编辑海报
     */
    @RequestMapping(value = "/{id}/modify", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> modify(DistributionPoster params) {
        try {
            Requires.hasLength(params.getBackground(), "请上传背景图片");
            distributionPosterApplication.modify(params.setMerchant(Securitys.currentUser()));
            return ImmutableMap.of("status", true, "message", "编辑成功");
        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            log.error("[编辑海报异常]", e);
            return ImmutableMap.of("status", false, "message", "编辑异常");
        }
    }


    /**
     * 海报预览
     *
     * @param poster 预览参数
     */
    @RequestMapping(value = "/preview", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> preview(DistributionPoster poster) {
        try {
            String image = distributionPosterApplication.generateTemplateImage(poster);
            return ImmutableMap.of("status", true, "message", "生成成功", "name", image, "url", storeDomain + "/uploads/" + image);
        } catch (Exception e) {
            log.error("[生成海报模板图异常]", e);
            return ImmutableMap.of("status", false, "message", "生成海报模板图异常");
        }
    }

}
